package com.deparse.dpframe.ui.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.deparse.dpframe.utils.DPLogUtil;

import java.util.List;

/**
 * Created by MartinDKent on 2016/3/23.
 */
public abstract class DPBaseAdapter<T> extends BaseAdapter {
    protected Context context;
    protected LayoutInflater inflater = null;
    protected List<T> data;

    public DPBaseAdapter(Context context) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    public DPBaseAdapter(Context context, List<T> data) {
        this.data = data;
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    public View inflate(int layoutId) {
        if (null == inflater) {
            DPLogUtil.e("inflater = null.");
            return null;
        }
        return inflater.inflate(layoutId, null);
    }

    public void update(List<T> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    public void removeData(int position) {
        if (null != data && position < data.size()) {
            data.remove(position);
        }
    }

    public void removeData(T obj) {
        if (null != data) {
            data.remove(obj);
        }
    }

    public List<T> getData() {
        return data;
    }

    public T getData(int position) {
        return null == data ? null : data.get(position);
    }

    @Override
    public int getCount() {
        return null == data ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return null == data ? null : (position < data.size() ? data.get(position) : null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CommonBaseViewHolder<T> holder;
        View view;

        if (null == convertView) {
            holder = getHolder(position);
            view = holder.create(position);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (CommonBaseViewHolder<T>) view.getTag();
        }
        if (position >= data.size()) {
            holder.update(position, null);
            return view;
        }
        holder.update(position, data.get(position));
        return view;
    }

    public abstract CommonBaseViewHolder<T> getHolder(int position);

    public static abstract class CommonBaseViewHolder<T> {

        public abstract View create(int position);

        public abstract void update(int position, T data);
    }
}
